<template>
    <a-popover v-model:visible="state.visible" title="导入excel" trigger="click" placement="bottom">
        <a-button :size="size" class="import-execl">
            <UploadOutlined />
            <slot></slot>
        </a-button>

        <template #content>
            <div class="import-execl-content">
                <a-upload
                    v-model:file-list="fileList"
                    name="file"
                    :multiple="false"
                    accept=".xlsx"
                    :action="state.action"
                    :headers="headers"
                    :beforeUpload="beforeUpload"
                    :disabled="state.disabled"
                    @change="handleChange"
                >
                    <a-button>
                        <FileExcelOutlined />选择Excel文件
                    </a-button>
                </a-upload>
            </div>
        </template>
    </a-popover>
</template>

<script lang="ts" setup>
import { reactive, ref, toRaw, withDefaults, defineProps } from 'vue';
import { message } from 'ant-design-vue';
import appsettings from '@/appsettings';
import { UserContext } from '@/utils/UserContext';

/**
 * 参数
 */
interface IProps {
    /**
     * 按钮大小
     */
    size?: string;

    /**
     * 导出excel表格地址
     */
    url: string;
}

const props = withDefaults(defineProps<IProps>(), {
    size: "small",
})

const emits = defineEmits(["onOk"]);

const state = reactive({
    visible: false,
    disabled: false,
    action: appsettings.ApiBaseURL + props.url
})


const handleChange = (info: any) => {
    if (info.file.status === 'done') {
        state.disabled = false;
        let response = toRaw(info.file.response);
        if (response.code != 0) {
            message.error(`${info.file.name} 导入失败, ${response.msg}`);
            return;
        }
        message.success(`${info.file.name} 导入成功`);
        emits("onOk", response);
        state.visible = false;
    } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 导入失败`);
    }
};

// components_bus
const headers = ref({
    Authorization: UserContext.getToken(),
});

const beforeUpload = () => {
    state.disabled = true;
}

const fileList = ref([]);

</script>

<style scoped>
.import-execl-content {
    min-width: 160px;
}
</style>